import {onBeforeUnmount, onMounted, type Ref, ref} from 'vue'
import type InputProps from "@/components/input/type/InputProps.ts";
import type InputEmits from "@/components/input/type/InputEmits.ts";

/**
 * created by yangtong on 2025/6/16 下午11:02
 * <br />
 * 数字输入框专用逻辑
 */
export function useNumberInput(props: InputProps,
                               emit: InputEmits,
                               displayValue: Ref<string>) {

    const numberInputRef = ref<HTMLInputElement>()

    // 数值增加
    const plus = () => {
        numberInputRef.value?.focus()
        const value = Number(props.modelValue)

        if (value >= props.max! || value < props.min!) {
            resetNumber()
            return
        }

        const finalValue = String(Math.min(value + props.step!, props.max!))
        displayValue.value = finalValue
        emit("update:modelValue", finalValue)
    }

    // 数值减少
    const minus = () => {
        numberInputRef.value?.focus()
        const value = Number(props.modelValue)

        if (value > props.max! || value <= props.min!) {
            resetNumber()
            return
        }

        const finalValue = String(Math.max(value - props.step!, props.min!))
        displayValue.value = finalValue
        emit("update:modelValue", finalValue)
    }

    // 重置数字到合法范围
    const resetNumber = () => {
        if (props.type !== "number") return

        const value = Number(props.modelValue)

        if (value < props.min!) {
            displayValue.value = String(props.min)
            emit("update:modelValue", String(props.min))
        }

        if (value > props.max!) {
            displayValue.value = String(props.max)
            emit("update:modelValue", String(props.max))
        }
    }

    // 上一次滚动时间
    let lastWheelTime = 0
    // 滚轮事件处理
    const onWheel = (e: WheelEvent) => {
        const currentWheelTime = Date.now()
        // 防抖检查
        if (currentWheelTime - lastWheelTime < 100) {
            console.warn('滚动太频繁，至少间隔100ms')
            return
        }

        if (document.activeElement !== e.target) return
        e.preventDefault()
        if (e.deltaY < 0) {
            plus()
        } else {
            minus()
        }

        // 更新时间戳
        lastWheelTime = currentWheelTime
    }

    // 生命周期
    onMounted(() => {
        const input = numberInputRef.value
        if (input && props.type === 'number') {
            input.addEventListener('wheel', onWheel, {passive: false})
            props.allows?.push((val: string) => /^\d*\.?\d*$/.test(val))
        }
    })

    onBeforeUnmount(() => {
        const input = numberInputRef.value
        if (input) {
            input.removeEventListener('wheel', onWheel)
        }
    })

    return {
        numberInputRef,
        plus,
        minus,
        resetNumber
    }

}